package xyz.doikki.dkplayer.activity.data;

import xyz.doikki.dkplayer.activity.data.model.LoggedInUser;
import xyz.doikki.dkplayer.app.MyApplication;
import xyz.doikki.dkplayer.bean.UserBean;
import xyz.doikki.dkplayer.util.DataUtil;
import xyz.doikki.dkplayer.util.Utils;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
public class LoginDataSource {

    public Result<LoggedInUser> login(String username, String password) {

        try {
            // TODO: handle loggedInUser authentication
            UserBean srcUserBean = new UserBean(username, password);
            List<UserBean> userBeans = DataUtil.getUserDataFromAssets(MyApplication.getInstance());
            boolean isAuthor = false;
            for(UserBean item : userBeans){
                if (item.equals(srcUserBean)) {
                    isAuthor = true;
                    break;
                }
            }
            if (isAuthor){
                LoggedInUser fakeUser = new LoggedInUser(UUID.randomUUID().toString(),
                        srcUserBean.user);
                return new Result.Success<>(fakeUser);
            }else {
                return new Result.Error(new Exception("用户名或密码错误！"));
            }
        } catch (Exception e) {
            return new Result.Error(new IOException("Error logging in", e));
        }
    }

    public void logout() {
        // TODO: revoke authentication
    }
}